//
//  ForgetPasswordViewController.swift
//  koolcar
//
//  Created by xiantian on 2023/9/15.
//

import UIKit
import RxSwift
class ForgetPasswordViewController: BaseViewController {
    var titleLab: UILabel!
    var phoneView: KInputTextField!
    var getCodeBtn: UIButton! //获取验证码
    var phone: String = ""
    var areaCodeBtn: UIButton!
    var disposeBag = DisposeBag()
    private var phoneAreaList: [PhoneAreaObj] = [] //手机区号

    override func viewDidLoad() {
        super.viewDidLoad()
        self.navBar.backgroundColor = UIColor.white
        self.navBar.wr_setBottomLineHidden(hidden: true)
        
        titleLab = UILabel()
        titleLab.textColor = Theme.mainColor
        titleLab.backgroundColor = UIColor.clear
        titleLab.font = UIFont.init(name: Theme.PingFangSCMedium, size: 26)
        titleLab.numberOfLines = 1
        titleLab.lineBreakMode = .byTruncatingTail
        titleLab.text = MMLocalizedString("forget_pwd", comment: "找回密码")
        titleLab.textAlignment = .center
        titleLab.adjustsFontSizeToFitWidth = true
        view.addSubview(titleLab)
        
        //账号
        phoneView = KInputTextField()
        phoneView.placeholder = MMLocalizedString("forget_please_enter_phone", comment: "请输入手机号码")
        areaCodeBtn = UIButton.init(frame: CGRect.init(x: 0, y: 0, width: 60, height: 54))
        phoneView.keyboardType = .numberPad
        areaCodeBtn.setup_titleColor(color: Theme.titleLabColor)
        var tempCode = XTManageCenter.getLocalStringDataValue(aKey: UtilCenter.phoneCodeKey)
        if tempCode == "" {
            let codeObj = XTManageCenter.getPhoneAreaCodeList().first
            tempCode = codeObj?.code ?? "852"
        }
        areaCodeBtn.setup_titleLabel(text: tempCode)
        areaCodeBtn.setup_image(image: UIImage.init(named: "icon_drop_full"))
        areaCodeBtn.titleLabel?.font = UIFont.init(name: Theme.PingFangSCRegular, size: 12)
        areaCodeBtn.semanticContentAttribute = .forceRightToLeft
        areaCodeBtn.backgroundColor = .white
        areaCodeBtn.titleEdgeInsets = UIEdgeInsets.init(top: 0, left: 0, bottom: 0, right: 5)
        areaCodeBtn.addTarget(self, action: #selector(self.areaCodeBtnAction), for: .touchUpInside)
        phoneView.leftView = areaCodeBtn
        view.addSubview(phoneView)

        getCodeBtn = UIButton()
        getCodeBtn.setup_titleLabel(text: MMLocalizedString("forget_get_code", comment: "获取验证码"))
        getCodeBtn.setup_titleColor(color: UIColor.white)
        getCodeBtn.setBackgroundImage(UIImage.image(withColor: Theme.mainColor), for: .normal)
        getCodeBtn.setBackgroundImage(UIImage.image(withColor: Theme.mainColorHighLightColor), for: .highlighted)
        getCodeBtn.titleLabel?.font = UIFont.init(name: Theme.PingFangSCMedium, size: 16)
        getCodeBtn.layer.cornerRadius = 8
        getCodeBtn.layer.masksToBounds = true
        getCodeBtn.addTarget(self, action: #selector(getCodeBtnAction), for: .touchUpInside)
        view.addSubview(getCodeBtn)
        
        self.addSnpLayout()
        self.bindMVVM()
        self.getPhoneAreaList()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
    }
    
    private func addSnpLayout(){
        titleLab.snp.makeConstraints { make in
            make.centerX.equalTo(kScreenWidth/2)
            make.height.equalTo(30)
            make.top.equalTo(NavBarHight + 60)
            make.width.greaterThanOrEqualTo(200)
        }
        
        phoneView.snp.makeConstraints { make in
            make.left.equalTo(30)
            make.right.equalTo(-30)
            make.top.equalTo(titleLab.snp.bottom).offset(68)
            make.height.greaterThanOrEqualTo(54)
        }
        
        getCodeBtn.snp.makeConstraints { make in
            make.left.equalTo(30)
            make.right.equalTo(-30)
            make.top.equalTo(phoneView.snp.bottom).offset(146)
            make.height.equalTo(46)
        }
    }
    
    private func bindMVVM(){
        self.phoneView.textField.rx.text.orEmpty.subscribe { txt in
            self.phone = txt
        }.disposed(by: self.disposeBag)
    }
    
    ///获取验证码
    @objc func getCodeBtnAction(){
        self.closeKeyboard()
        if self.phone == "" {
            self.phoneView.warnText = MMLocalizedString("forget_please_enter_phone", comment: "请输入手机号码")
            return
        }
        
        if XTManageCenter.judgeTextIsPhoneNumber(text: self.phone) == false {
            self.phoneView.warnText = MMLocalizedString("forget_please_enter_real_phone", comment: "请输入正确的手机号码")
            return
        }
        
        let areaCode = XTManageCenter.getLocalStringDataValue(aKey: UtilCenter.phoneCodeKey)
        let param: [String: String] = ["mobileAreaCode": areaCode,
                                       "phone": self.phone,
                                       "sendType": "2"]
        self.view.showLoadingHUDText()
        XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.captchaGetCode(param: param), objectType: SMSCodeModel.self) { data in
            self.view.handleLoading()
            let resultObj = data as? SMSCodeModel
            guard let code = resultObj?.code, code == "1" else {
                self.view.makeToast(message: resultObj?.msg ?? "")
                return
            }
            self.jumpToVerify()
//            XTAlertView.showAlertView(title: "当前验证码", message: resultObj?.data ?? "", cancelButtonTitle: "确定") { alertView, buttonIndex in
//                self.jumpToVerify()
//            }
        } error: { err in
            self.view.handleLoading()
            self.view.makeToast(message: err?.domain ?? "")
        }
    }
    
    private func closeKeyboard(){
        self.phoneView.textField.resignFirstResponder()
    }
    
    private func getPhoneAreaList(){
        XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.commonMemberAreaCode(param: ["":""]), objectType: PhoneAreaResModel.self) { data in
            let resultObj = data as? PhoneAreaResModel
            guard resultObj?.code == "1" else {
                self.phoneAreaList = [PhoneAreaObj.init(code: "852")]
                self.setDefaultAreaCode()
                return
            }
            
            let codeJson = resultObj?.data?.areaCode ?? ""
            var codeList = [PhoneAreaCodeModel].init(JSONString: codeJson) ?? []
            
            if codeList.count == 0 {
                //默认852
                self.phoneAreaList = [PhoneAreaObj.init(code: "852")]
            }else if codeList.count == 1 {
                let code = codeList.first?.areacode ?? "852"
                self.phoneAreaList = [PhoneAreaObj.init(code: code)]
            }else {
                codeList = codeList.sorted(by: { res1, res2 in
                    return res1.order ?? "852" < res2.order ?? "852"
                })
                
                self.phoneAreaList = []
                codeList.forEach { tempItem in
                    let item = PhoneAreaObj.init(code: tempItem.areacode ?? "")
                    self.phoneAreaList.append(item)
                }
            }
            self.setDefaultAreaCode()
        } error: { err in
            //默认852
            self.phoneAreaList = [PhoneAreaObj.init(code: "852")]
            self.setDefaultAreaCode()
        }
    }
    
    ///默认codeArea
    private func setDefaultAreaCode(){
        let code = XTManageCenter.getLocalStringDataValue(aKey: UtilCenter.phoneCodeKey)
        if code == "" {
            let tempCode = self.phoneAreaList.first?.code ?? ""
            self.areaCodeBtn.setup_titleLabel(text: tempCode)
            XTManageCenter.setLocalDataString(aKey: UtilCenter.phoneCodeKey, aValue: tempCode)
        }
    }
    
    ///区号选择
    @objc func areaCodeBtnAction(){
        self.closeKeyboard()
        let vc = PhoneAreaPickerVC()
        vc.dataArray = self.phoneAreaList
        vc.modalPresentationStyle = .overFullScreen
        vc.callBack = { [weak self] codeObj in
            self?.areaCodeBtn.setup_titleLabel(text: codeObj.code)
            XTManageCenter.setLocalDataString(aKey: UtilCenter.phoneCodeKey, aValue: codeObj.code)
        }
        self.present(vc, animated: false)
    }
    
    ///跳转
    private func jumpToVerify(){
        let vc = InputVerifyViewController()
        vc.phoneStr = self.phone
        vc.pageType = .forgetPassword
        self.navigationController?.pushViewController(vc, animated: true)
    }
}
